# 统一异常捕获处理
#coding=utf-8
from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from src.utils.respone import fail,success
import re

def register_exception(app: FastAPI):

    """
    重写捕获字段验证报错
    """
    @app.exception_handler(RequestValidationError)
    def handler_try_Validation(request: Request, err: RequestValidationError):
        print("err.body==", err.errors())
        msg = err.errors()[0].get("msg")
        if msg == "field required":
            msg = "请求失败，缺少必填项！"
        elif msg == "value is not a valid list":
            print(err.errors())
            msg = f"类型错误，提交参数应该为列表！"
        elif msg == "value is not a valid int":
            msg = f"类型错误，提交参数应该为整数！"
        elif msg == "value could not be parsed to a boolean":
            msg = f"类型错误，提交参数应该为布尔值！"
        elif msg == "Input should be a valid list":
            msg = f"类型错误，输入应该是一个有效的列表！"
        elif re.match(r'Value error', msg):
            arr = re.match(r'Value error', msg)
            startIndex = arr.span()[1] + 1 # 加1是为了去掉逗号
            msg = msg[startIndex:].strip() # strip()去掉字符串左右空白
         
        return fail(msg)